<template>
    <Modal class="employee-edit"
           title="填写员工信息"
           ok-text="保存"
           width="800"
           :styles="{margin:'0 atuo', zIndex:100}"
           v-model="show"
           :mask-closable="false"  @on-cancel="cancel">
        <Form ref="employeeForm" :model="form" :rules="ruleValidate" :label-width="120" style="padding: 20px">
            <FormItem label="头像" porp="avatarFile">
                <div style="position: relative">
                    <img class="home-photo" ref="avatar" style="cursor:pointer;display: inline-block" @click="selImg" :src="avatarFile||defaultImg" title="点击修改图片">
                    <div style="visibility:hidden;position: absolute;top:0">
                        <input type="file" ref="file" style="line-height: 18px" accept="image/jpg,image/jpeg,image/png" @change="getImg">
                    </div>
                </div>
            </FormItem>
            <FormItem label="姓名" prop="employeeName">
                <Input v-model="form.employeeName" clearable style="width:200px" placeholder="请输入姓名" :maxlength="255"/>
            </FormItem>
            <FormItem label="用户名" prop="userName" v-if="form.id">
                <span>{{form.userName}}</span>
            </FormItem>
            <FormItem label="密码" prop="password">
                <Input v-model="form.password" type="text" style="width:200px;display: inline-block" placeholder="请输入密码" disabled  v-if="mode === 'add'"/>
                <Input v-model="form.password" clearable type="password" style="width:200px;display: inline-block" placeholder="请输入密码" v-if="mode === 'edit'"/>
                <span class="label" style="color: #bbb">字母、符号和数字组合设置，密码长度6~16字符</span>
            </FormItem>
            <FormItem label="昵称" prop="nickName">
                <Input v-model="form.nickName" clearable style="width:200px" placeholder="请输入昵称" :maxlength="255"/>
            </FormItem>
            <FormItem label="性别" prop="gender">
                <RadioGroup v-model="form.gender" style="line-height: 32px;height: 32px">
                    <Radio label="true">男</Radio>
                    <Radio label="false">女</Radio>
                    <!--<Radio label="undefined">保密</Radio>-->
                </RadioGroup>
            </FormItem>
            <FormItem label="选择部门" prop="orgStructId">
                <Button type="primary" @click="showOrgModal=!showOrgModal">组织架构</Button>
                <span class="label" style="color: red">{{orgTitle}}</span>
                <ChooseOrgStructure :showModal="showOrgModal" @toggleOrgStructModal="toggleOrgModal" @orgStructSelected="setOrgStructure"></ChooseOrgStructure>
            </FormItem>
            <FormItem label="选择职能" prop="orgFuncIds">
                <Button type="primary" @click="showDutyModal=!showDutyModal">职能分类</Button>
                <span class="label" style="color: red">{{dutyTitle}}</span>
                <ChooseDuty :showModal="showDutyModal" @toggleDutyModal="toggleDutyModal" @dutySelected="setDuty"></ChooseDuty>
            </FormItem>
            <FormItem label="联系方式" prop="contact">
                <Input v-model="form.contact" clearable style="width:200px" placeholder="请输入联系方式"/>
            </FormItem>
            <FormItem label="腾讯通" prop="rtx">
                <Input v-model="form.rtx" clearable style="width:200px" placeholder="请输入腾讯通" :maxlength="255"/>
            </FormItem>
            <FormItem label="邮箱" prop="email">
                <Input type="email" v-model="form.email" clearable style="width:200px" placeholder="请输入邮箱"/>
            </FormItem>
            <FormItem label="入职时间" prop="entryTime">
                <DatePicker type="date" v-model="form.entryTime" clearable style="width:200px" placeholder="年/月/日"></DatePicker>
                <span class="label" style="color: #bbb">注:不填写即默认为当前时间</span>
            </FormItem>
            <FormItem label="出生时间" prop="birthdate">
                <DatePicker type="date" v-model="form.birthdate" clearable style="width:200px" placeholder="年/月/日"></DatePicker>
                <!--<span class="label" style="color: red">注:不填写即默认为当前时间</span>-->
            </FormItem>
            <FormItem label="员工状态" prop="status">
                <Select v-model="form.status" placeholder="请输入员工状态" style="width:200px">
                    <Option v-for="item in employeeStatusOpts" :value="item.val" :key="item.val">{{ item.label }}</Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button @click="addEmployee" type="primary">提交</Button>
        </div>
    </Modal>
</template>

<script>
    import * as employeeOpr from '../../http/employee.api'
    import ChooseOrgStructure from './ChooseOrgStructure.vue'
    import ChooseDuty from './ChooseDuty.vue'
    export default {
        props: ['showModal', 'employeeInfo','mode','parentMessage'],
        name: "EmployeeEdit",
        components: {
            ChooseOrgStructure,
            ChooseDuty
        },
        data() {
            const valideNewPassword = (rule, value, callback) => {
                let patrn = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\.!@#$%^&*?~'\+\*\-:;^_`]+$)[,\.!@#$%^&*?~'\+\*\-:;^_`0-9A-Za-z]{6,16}$/
                if(value&&!patrn.exec(value)) {
                   callback(new Error('密码需是字母、符号或数字组合'))
                } else {
                    callback()
                }
            }
            const valideTel = (rule, value, callback) => {
                let tel = /^0?(13[0-9]|15[012356789]|17[0135678]|18[0-9]|14[579])[0-9]{8}$/
                if(value && !tel.test(value)) {
                    callback(new Error('联系方式格式不正确'))
                } else {
                    callback()
                }
            }
            return {
                show: false, // 控制当前模块显示关闭
                chooseOrgStruct: '',
                chooseDuty: [],
                showOrgModal: false,
                showDutyModal: false,
                defaultImg: '/static/image/default_icon.jpg',
                "avatarFile": undefined, // 头像 multipart文件上传
                form: {
                    "employeeName": undefined, // 员工姓名
                    "userName": undefined, // 用户名
                    "password": '123456abc', // 密码
                    "nickName": undefined, // 昵称
                    "gender": 'true', //性别 true男 false女
                    "contact": undefined, //联系方式
                    "rtx": undefined, // 腾讯通
                    "email": undefined, //邮箱
                    "entryTime": new Date(), //入职时间
                    "birthdate": new Date(), // 出生日期
                    "status": "normal", // 状态 normal正常 forbidden禁用 disable离职
                    "orgStructId": undefined, // 组织架构id
                    "orgFuncIds": [] // 职能id集合
                },
                employeeStatusOpts: [
                    {label: '正常', val: 'normal'},
                    {label: '禁用', val: 'forbidden'},
                    {label: '离职', val: 'disable'}
                ],
                visible: false,

                ruleValidate: {
                    employeeName: [
                        { required: true, message: '用户姓名不能为空', trigger: 'blur' }
                    ],
                    password: [
                        // { required: true, message: '新增密码不能为空', trigger: 'blur' },
                        { validator: valideNewPassword, trigger: 'blur' },
                    ],
                    email: [
                        { type: 'email', message: '电子邮件不正确', trigger: 'change' }
                    ],
                    contact: [
                        { validator: valideTel, trigger: 'blur' }
                    ],
                    orgStructId: [
                        // { required: true, message: '组织架构不能为空', trigger: 'change' }
                    ],
                    orgFuncIds: [
                        // { required: true, message: '职能不能为空', trigger: 'change' }
                    ],
                },
            }
        },
        computed: {
            orgTitle: function () {
                const _this = this;
                return _this.chooseOrgStruct&&_this.chooseOrgStruct.path;
            },
            dutyTitle: function () {
                const _this = this;
                return _this.chooseDuty.map(item => item.title||item.funcName).join(' , ');
            },
        },
        watch: {
            show: function (newVal, oldVal) { // 控制当前模块是否显示
                this.$emit('toggleModal', newVal);
            },
            showModal: function (newVal, oldVal) { // 属性，外部接收过来
                this.show = newVal;
            },
            employeeInfo: function (newVal, oldVal) {
                const _this = this;
                // console.log(JSON.stringify(newVal), JSON.stringify(oldVal));
                // 收到 外部值，传递给内部
                if (newVal) {
                    // console.log(JSON.stringify(newVal))
                    // 处理性别
                    // newVal.gender = newVal.gender === true ? 'true' : newVal.gender === false ? 'false' : undefined;
                    newVal.gender = newVal.gender === true ? 'true' : 'false';
                    newVal.entryTime = newVal.entryTime ? new Date(newVal.entryTime) : new Date();
                    newVal.birthdate = newVal.birthdate ? new Date(newVal.birthdate) : new Date();
                    // newVal.password = undefined;

                    // 编辑时候
                    _this.chooseOrgStruct = newVal.id&&Object.assign({}, newVal, {path: newVal.orgStruct&&newVal.orgStruct.dept||''})||undefined;
                    _this.chooseDuty = newVal.id&&[].concat(newVal.orgFuncs||[])||[];



                    _this.form = Object.assign({
                        "password": '123456abc',
                        "gender": 'true', //性别 true男 false女
                        "entryTime": new Date(),    //入职时间
                        "birthdate": new Date(),    // 出生日期
                        "status": "normal",         // 状态 normal正常 forbidden禁用 disable离职
                        "orgFuncIds": []            // 职能id集合

                    }, newVal, {path: newVal.id&&newVal.orgStruct&&newVal.orgStruct.dept||undefined, orgFuncIds: newVal.orgFuncs&&newVal.orgFuncs.map(item => item.id)||[]});
                    if (newVal.id) {
                        _this.$refs.file.src = 'http://192.168.1.249' + newVal.avatar;
                        _this.avatarFile = 'http://192.168.1.249' + newVal.avatar;
                    } else {
                        _this.avatarFile = undefined;
                    }
                    if(newVal.avatar == null){
                        _this.avatarFile = _this.defaultImg
                    }
                    // console.log(_this.form)
                }
            }
        },
        mounted() {
            const _this = this;
            // console.log('mounted', this.showModal);
            // console.log('mounted', JSON.stringify(this.employeeInfo));
        },
        created() {
            // console.log('created', JSON.stringify(this.employeeInfo));
        },
        methods: {
            cancel () {
                this.$refs['employeeForm'].resetFields();
            },
            // 上传头像
            selImg: function () {
                const _this = this;
                _this.$refs.file.click() // 触发图片上传
            },
            getImg() {
                const _this = this;
                var imgs = _this.$refs['file'].files[0]
                var reader = new window.FileReader()
                reader.onload = (e) => {
                    _this.avatarFile = e.target.result
                    // console.log(_this.avatarFile)
                }
                // reader.readAsArrayBuffer(imgs) // 将file读取为ArrayBuffer
                reader.readAsDataURL(imgs) // 将file读取为Url
            },
            addEmployee() {
                const _this = this;
                let params = Object.assign({}, _this.form);
                // 必填校验
                // if (!_this.form.employeeName) {
                //     return _this.$Message.warning('员工姓名必填');
                // }
                // if (!_this.form.id&&!_this.form.password) {  "^[\\^\\$\\.\\\\,;:'!@#%&~`_-+=<>\"\\*\\|\\?\\+\\(\\)\\[\\]\\{\\}0-9a-zA-Z]{6,16}$"
                //     return _this.$Message.warning('新增时密码必填');
                // }
                // if (!_this.form.id) {
                //     if (!new RegExp("^[\\\\,;:'\"!@#%&~`_=<>\\^\\$\\.\\-\\*\\|\\?\\+\\(\\)\\[\\]\\{\\}0-9a-zA-Z]{6,16}$").test(_this.form.password)) {
                //         return _this.$Message.warning('密码格式有误');
                //     }
                // }
                // if (!_this.form.orgStructId) {
                //     return _this.$Message.warning('请选择组织机构');
                // }
                // if (_this.form.orgFuncIds.length<1) {
                //     return _this.$Message.warning('请选择职能');
                // }
                // if (!_this.form.status) {
                //     return _this.$Message.warning('请选择员工状态');
                // }
                params.gender = _this.form.gender === 'true' ? true : _this.form.gender === 'false' ? false : undefined;
                params.entryTime = params.entryTime&&new Date(params.entryTime).getTime()||undefined;
                params.birthdate = params.birthdate&&new Date(params.birthdate).getTime()||undefined;
                _this.$refs['employeeForm'].validate((valid) => {
                    if (valid) {
                        employeeOpr[params.id&&'update'||'add'](params, _this.$refs['file'].files[0]).then(res => {
                            console.log(res.data);
                            _this.$Message.success('保存成功!')
                            _this.show = false;
                            resolve()
                        }).catch(err => {
                            console.log(err);
                            _this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                            // reject()

                        });
                    } else {
                        // this.$Message.error('保存失败!')
                    }
                });

            },
            toggleOrgModal(show) {
                this.showOrgModal = show;
            },
            toggleDutyModal(show) {
                this.showDutyModal = show;
            },
            setOrgStructure(selectedRec) {
                const _this = this;
                console.log(JSON.stringify(selectedRec))
                _this.chooseOrgStruct = selectedRec;
                _this.form.orgStructId = selectedRec.origin.id;
                // _this.orgTitle = selectedRec.path;
                console.log(_this.form)
            },
            setDuty(selectedRecs) {
                const _this = this;
                _this.chooseDuty = selectedRecs;
                _this.form.orgFuncIds = selectedRecs.map(item => item.origin.id);
                // _this.dutyTitle = selectedRecs.map(item => item.title).join(' | ');
                console.log(_this.form)
            }
        }
    }
</script>

<style scoped>
    .employee-edit .ivu-modal-wrap{
        z-index: 9000;
    }
    .employee-edit .ivu-modal{
        z-index: 9000;
    }
    .employee-edit  .label, .employee-edit  .label-right {
        line-height: 32px;
        display: inline-block;
    }
    .employee-edit .ivu-form-item {
        margin-bottom: 20px;
    }
</style>
